<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>浏览书籍 - 用户端</title>
    <link href="https://fonts.googleapis.com/css?family=Roboto:400,700&display=swap" rel="stylesheet">
    <style>
        body {
            background: linear-gradient(120deg, #a1c4fd 0%, #c2e9fb 100%);
            font-family: 'Roboto', sans-serif;
            min-height: 100vh;
            margin: 0;
        }
        .layout {
            display: flex;
            min-height: 100vh;
        }
        .sidebar {
            width: 210px;
            background: #fff;
            box-shadow: 2px 0 16px rgba(0,0,0,0.07);
            display: flex;
            flex-direction: column;
            padding: 32px 0 0 0;
        }
        .sidebar-title {
            font-size: 1.3rem;
            font-weight: 700;
            color: #2d3a4b;
            text-align: center;
            margin-bottom: 36px;
        }
        .nav {
            display: flex;
            flex-direction: column;
            gap: 8px;
        }
        .nav a {
            display: block;
            padding: 12px 32px;
            color: #4a5a6a;
            text-decoration: none;
            font-size: 1.08rem;
            border-left: 4px solid transparent;
            transition: background 0.2s, color 0.2s, border-color 0.2s;
        }
        .nav a.active, .nav a:hover {
            background: #eaf3ff;
            color: #3478f6;
            border-left: 4px solid #7eb6ff;
        }
        .logout-btn {
            margin: 32px 24px 0 24px;
            padding: 12px 0;
            width: calc(100% - 48px);
            background: linear-gradient(90deg, #ff6b6b 0%, #ffb36b 100%);
            color: #fff;
            font-weight: 700;
            border: none;
            border-radius: 8px;
            font-size: 1.08rem;
            cursor: pointer;
            transition: background 0.2s;
        }
        .logout-btn:hover {
            background: linear-gradient(90deg, #ffb36b 0%, #ff6b6b 100%);
        }
        .content {
            flex: 1;
            display: flex;
            justify-content: center;
            align-items: flex-start;
            min-height: 100vh;
            padding: 48px 32px;
        }
        .container {
            background: #fff;
            padding: 36px 28px 28px 28px;
            border-radius: 16px;
            box-shadow: 0 8px 32px rgba(0,0,0,0.15);
            width: 1100px;
            max-width: calc(100vw - 210px - 64px);
        }
        .title {
            font-size: 1.7rem;
            font-weight: 700;
            color: #2d3a4b;
            margin-bottom: 24px;
            text-align: center;
        }
        .search-section {
            display: flex;
            justify-content: flex-end;
            align-items: center;
            margin-bottom: 24px;
            gap: 16px;
        }
        .search-input {
            padding: 8px 12px;
            border: 1px solid #d1d9e6;
            border-radius: 6px;
            font-size: 0.95rem;
            outline: none;
            transition: border 0.2s;
            width: 220px;
        }
        .search-input:focus {
            border-color: #7eb6ff;
        }
        .search-btn, .reset-btn {
            padding: 8px 16px;
            border: 1px solid #d1d9e6;
            border-radius: 6px;
            background: #fff;
            color: #4a5a6a;
            font-size: 0.95rem;
            cursor: pointer;
            transition: all 0.2s;
        }
        .search-btn:hover, .reset-btn:hover {
            background: #f5f8fa;
            border-color: #7eb6ff;
        }
        .table-container {
            max-height: calc(100vh - 300px);
            overflow-y: auto;
            border: 1px solid #e3e8ee;
            border-radius: 8px;
        }
        table {
            width: 100%;
            border-collapse: collapse;
        }
        th, td {
            padding: 12px 8px;
            border-bottom: 1px solid #e3e8ee;
            text-align: center;
        }
        th {
            background: #f5f8fa;
            color: #4a5a6a;
            font-weight: 700;
            position: sticky;
            top: 0;
            z-index: 10;
        }
        .book-title {
            max-width: 200px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            cursor: help;
        }
        .actions button {
            margin: 0 4px;
            padding: 6px 14px;
            border: none;
            border-radius: 6px;
            font-size: 0.98rem;
            cursor: pointer;
            color: #fff;
            background: #7eb6ff;
            transition: background 0.2s;
        }
        .actions button.view { background: #6dd47e; }
        .actions button.view:hover { background: #5bc06d; }
        .pagination {
            display: flex;
            justify-content: flex-end;
            align-items: center;
            gap: 8px;
            margin-top: 18px;
            font-size: 15px;
        }
        .pagination button {
            padding: 6px 16px;
            border: none;
            border-radius: 4px;
            background: #f5f5f5;
            color: #3478f6;
            cursor: pointer;
            transition: background 0.2s, color 0.2s;
        }
        .pagination button:disabled {
            background: #f5f5f5;
            color: #ccc;
            cursor: not-allowed;
        }
        .pagination .page-info {
            margin: 0 8px;
            color: #333;
        }
        .pagination select {
            margin: 0 4px;
            padding: 4px 8px;
            border-radius: 4px;
            border: 1px solid #d1d9e6;
        }
        .loading {
            text-align: center;
            color: #666;
            font-style: italic;
            padding: 20px;
        }
        .error {
            color: #ff6b6b;
            text-align: center;
            padding: 20px;
        }
        /* 弹窗样式 */
        .modal-mask {
            position: fixed;
            left: 0; top: 0; right: 0; bottom: 0;
            background: rgba(0,0,0,0.18);
            z-index: 1000;
            display: none;
            align-items: center;
            justify-content: center;
        }
        .modal-card {
            background: #fff;
            border-radius: 18px;
            box-shadow: 0 12px 40px rgba(0,0,0,0.18);
            min-width: 420px;
            max-width: 98vw;
            padding: 38px 38px 28px 38px;
            position: relative;
            animation: fadeIn 0.2s;
        }
        .modal-title {
            font-size: 1.4rem;
            font-weight: 800;
            color: #2d3a4b;
            margin-bottom: 12px;
            letter-spacing: 1px;
            text-align: center;
        }
        .modal-divider {
            width: 100%;
            height: 1px;
            background: #e3e8ee;
            margin-bottom: 22px;
            border: none;
        }
        .modal-close {
            position: absolute;
            right: 18px;
            top: 18px;
            font-size: 1.3rem;
            color: #aaa;
            background: none;
            border: none;
            cursor: pointer;
        }
        .modal-row {
            display: flex;
            align-items: flex-start;
            margin-bottom: 18px;
        }
        .modal-label {
            width: 110px;
            color: #888;
            font-weight: 500;
            text-align: right;
            flex-shrink: 0;
            margin-right: 10px;
            letter-spacing: 1px;
        }
        .modal-value {
            color: #222;
            word-break: break-all;
            text-align: left;
            flex: 1;
        }
        .modal-value strong {
            font-weight: 700;
        }
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(30px); }
            to { opacity: 1; transform: translateY(0); }
        }
    </style>
    <script type="module">
        import { API_BASE_URL } from './api_config.js';
        window.API_BASE_URL = API_BASE_URL;
    </script>
</head>
<body>
    <div class="layout">
        <aside class="sidebar">
            <div class="sidebar-title">用户中心</div>
            <nav class="nav">
                <a href="user_books.html" class="active">浏览书籍</a>
                <a href="user_orders.html">我的订单</a>
                <a href="user_profile.html">个人信息</a>
            </nav>
            <button id="logoutBtn" class="logout-btn">退出登录</button>
        </aside>
        <main class="content">
            <div class="container">
                <div class="title">浏览书籍</div>
                <div class="search-section">
                    <input type="text" id="searchInput" class="search-input" placeholder="搜索书名...">
                    <input type="text" id="authorInput" class="search-input" placeholder="搜索作者名...">
                    <button id="searchBtn" class="search-btn">搜索</button>
                    <button id="resetBtn" class="reset-btn">重置</button>
                </div>
                <div class="table-container">
                    <table id="bookTable">
                        <thead>
                            <tr>
                                <th>书籍ID</th>
                                <th>书名</th>
                                <th>作者</th>
                                <th>价格</th>
                                <th>库存</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody id="bookTableBody">
                            <!-- 数据由JS渲染 -->
                        </tbody>
                    </table>
                </div>
                <div id="loadingMessage" class="loading" style="display: none;">正在加载书籍数据...</div>
                <div id="errorMessage" class="error" style="display: none;"></div>
                <div class="pagination" id="pagination" style="display: none;"></div>
            </div>
        </main>
    </div>
    <!-- 书籍详情弹窗 -->
    <div class="modal-mask" id="bookModalMask">
        <div class="modal-card">
            <button class="modal-close" id="bookModalClose">×</button>
            <div class="modal-title">预定书籍</div>
            <hr class="modal-divider" />
            <div id="bookModalContent">
                <!-- 动态填充 -->
            </div>
        </div>
    </div>
    <script>
    (function() {
        var apiBaseUrl = window.API_BASE_URL || 'http://localhost:3010';
        var currentPage = 1;
        var pageSize = 10;
        var totalPages = 0;
        var totalRecords = 0;
        var searchKeyword = '';
        var searchAuthor = '';

        function loadBooks() {
            showLoading();
            const params = new URLSearchParams({
                pageNum: currentPage,
                pageSize: pageSize
            });
            if (searchKeyword) params.append('bookName', searchKeyword);
            if (searchAuthor) params.append('author', searchAuthor);
            fetch(`${apiBaseUrl}/book/userPage?${params}`)
                .then(response => response.json())
                .then(data => {
                    hideLoading();
                    if (data.success && data.code === 200) {
                        displayBooks(data.data);
                        updatePagination(data.data);
                    } else {
                        showError('加载书籍失败: ' + (data.message || '未知错误'));
                    }
                })
                .catch(error => {
                    hideLoading();
                    showError('网络错误，请检查网络连接');
                });
        }

        function displayBooks(data) {
            const tbody = document.getElementById('bookTableBody');
            tbody.innerHTML = '';
            if (data.records && data.records.length > 0) {
                data.records.forEach(book => {
                    const row = document.createElement('tr');
                    row.innerHTML = `
                        <td>${book.id}</td>
                        <td class="book-title" title="${book.title}">${book.title}</td>
                        <td>${book.author}</td>
                        <td>￥${book.price}</td>
                        <td>${book.stock}</td>
                        <td class="actions">
                            <button class="view" onclick="reserveBook(${book.id})">预定</button>
                        </td>
                    `;
                    tbody.appendChild(row);
                });
            } else {
                tbody.innerHTML = '<tr><td colspan="6" style="text-align: center; color: #666;">暂无书籍数据</td></tr>';
            }
        }

        function updatePagination(data) {
            const pagination = document.getElementById('pagination');
            totalPages = data.pages;
            totalRecords = data.total;
            // 分页控件始终显示
            pagination.style.display = 'flex';
            pagination.innerHTML = '';
            // 上一页
            const prevBtn = document.createElement('button');
            prevBtn.textContent = '上一页';
            prevBtn.disabled = currentPage === 1;
            prevBtn.onclick = () => {
                if (currentPage > 1) {
                    currentPage--;
                    loadBooks();
                }
            };
            pagination.appendChild(prevBtn);
            // 页码信息
            const pageInfo = document.createElement('span');
            pageInfo.className = 'page-info';
            pageInfo.textContent = `第 ${currentPage} / ${totalPages} 页`;
            pagination.appendChild(pageInfo);
            // 下一页
            const nextBtn = document.createElement('button');
            nextBtn.textContent = '下一页';
            nextBtn.disabled = currentPage === totalPages;
            nextBtn.onclick = () => {
                if (currentPage < totalPages) {
                    currentPage++;
                    loadBooks();
                }
            };
            pagination.appendChild(nextBtn);
            // 每页显示
            const pageSizeLabel = document.createElement('span');
            pageSizeLabel.textContent = '每页显示:';
            pageSizeLabel.style.marginLeft = '12px';
            pagination.appendChild(pageSizeLabel);
            const pageSizeSelect = document.createElement('select');
            [10, 20, 30, 50].forEach(size => {
                const option = document.createElement('option');
                option.value = size;
                option.textContent = size;
                if (size === pageSize) option.selected = true;
                pageSizeSelect.appendChild(option);
            });
            pageSizeSelect.onchange = function() {
                pageSize = parseInt(this.value);
                currentPage = 1;
                loadBooks();
            };
            pagination.appendChild(pageSizeSelect);
            const pageSizeUnit = document.createElement('span');
            pageSizeUnit.textContent = '条';
            pagination.appendChild(pageSizeUnit);
        }

        function showLoading() {
            document.getElementById('loadingMessage').style.display = 'block';
            document.getElementById('errorMessage').style.display = 'none';
            document.getElementById('bookTable').style.display = 'none';
            document.getElementById('pagination').style.display = 'none';
        }
        function hideLoading() {
            document.getElementById('loadingMessage').style.display = 'none';
            document.getElementById('bookTable').style.display = 'table';
        }
        function showError(message) {
            document.getElementById('errorMessage').textContent = message;
            document.getElementById('errorMessage').style.display = 'block';
            document.getElementById('bookTable').style.display = 'none';
            document.getElementById('pagination').style.display = 'none';
        }

        document.getElementById('searchBtn').addEventListener('click', function() {
            searchKeyword = document.getElementById('searchInput').value.trim();
            searchAuthor = document.getElementById('authorInput').value.trim();
            currentPage = 1;
            loadBooks();
        });
        document.getElementById('resetBtn').addEventListener('click', function() {
            document.getElementById('searchInput').value = '';
            document.getElementById('authorInput').value = '';
            searchKeyword = '';
            searchAuthor = '';
            currentPage = 1;
            loadBooks();
        });
        document.getElementById('searchInput').addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                document.getElementById('searchBtn').click();
            }
        });
        document.getElementById('authorInput').addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                document.getElementById('searchBtn').click();
            }
        });
        // 预定弹窗
        window.reserveBook = function(bookId) {
            const mask = document.getElementById('bookModalMask');
            const content = document.getElementById('bookModalContent');
            content.innerHTML = '<div style="text-align:center;color:#888;">加载中...</div>';
            mask.style.display = 'flex';
            fetch(`${apiBaseUrl}/book/${bookId}`)
                .then(res => res.json())
                .then(data => {
                    if (data.success && data.code === 200) {
                        const book = data.data;
                        // 获取用户信息
                        var userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}');
                        var buyerId = userInfo.userId;
                        // 预定弹窗内容
                        content.innerHTML = `
                            <div class=\"modal-row\"><span class=\"modal-label\">书名：</span><span class=\"modal-value\">${book.title}</span></div>
                            <div class=\"modal-row\"><span class=\"modal-label\">作者：</span><span class=\"modal-value\">${book.author}</span></div>
                            <div class=\"modal-row\"><span class=\"modal-label\">价格：</span><span class=\"modal-value\">￥${book.price}</span></div>
                            <div class=\"modal-row\"><span class=\"modal-label\">库存：</span><span class=\"modal-value\" id=\"bookStock\">${book.stock}</span></div>
                            <div class=\"modal-row\"><span class=\"modal-label\">预定数量：</span><span class=\"modal-value\"><input type=\"number\" id=\"reserveQuantity\" min=\"1\" max=\"${book.stock}\" value=\"1\" style=\"width:80px;\"></span></div>
                            <div style=\"text-align:center;margin-top:18px;\"><button id=\"reserveConfirmBtn\" style=\"padding:8px 32px;border-radius:8px;background:#3478f6;color:#fff;font-weight:700;border:none;font-size:1.08rem;cursor:pointer;\">确认预定</button></div>
                            <div id=\"reserveError\" style=\"color:#ff6b6b;text-align:center;margin-top:10px;display:none;\"></div>
                        `;
                        document.getElementById('reserveConfirmBtn').onclick = function() {
                            var quantity = parseInt(document.getElementById('reserveQuantity').value);
                            var stock = parseInt(document.getElementById('bookStock').textContent);
                            if (isNaN(quantity) || quantity < 1) {
                                showReserveError('请输入正确的预定数量');
                                return;
                            }
                            if (quantity > stock) {
                                showReserveError('预定数量不能超过库存');
                                return;
                            }
                            // 发送预定请求
                            fetch(`${apiBaseUrl}/bookOrder`, {
                                method: 'POST',
                                headers: { 'Content-Type': 'application/json' },
                                body: JSON.stringify({
                                    bookId: book.id,
                                    merchantId: book.merchantId,
                                    buyerId: buyerId,
                                    quantity: quantity
                                })
                            })
                            .then(res => res.json())
                            .then(data => {
                                if (data.success) {
                                    content.innerHTML = '<div style=\"color:#28a745;text-align:center;font-size:1.15rem;\">预定成功！</div>';
                                    setTimeout(() => { mask.style.display = 'none'; loadBooks(); }, 1200);
                                } else {
                                    showReserveError(data.message || '预定失败');
                                }
                            })
                            .catch(() => {
                                showReserveError('网络错误，预定失败');
                            });
                        };
                        function showReserveError(msg) {
                            var err = document.getElementById('reserveError');
                            err.textContent = msg;
                            err.style.display = 'block';
                        }
                    } else {
                        content.innerHTML = '<div style="color:#ff6b6b;text-align:center;">加载失败: '+(data.message||'未知错误')+'</div>';
                    }
                })
                .catch(() => {
                    content.innerHTML = '<div style="color:#ff6b6b;text-align:center;">网络错误，无法加载书籍详情</div>';
                });
        };
        // 关闭弹窗
        document.getElementById('bookModalClose').onclick = function() {
            document.getElementById('bookModalMask').style.display = 'none';
        };
        document.getElementById('bookModalMask').onclick = function(e) {
            if (e.target === this) this.style.display = 'none';
        };
        // 初始加载
        loadBooks();
        // 每30秒自动刷新
        var bookAutoRefreshTimer = setInterval(loadBooks, 30000);
        window.addEventListener('beforeunload', function() { clearInterval(bookAutoRefreshTimer); });
        // 退出登录
        document.getElementById('logoutBtn').onclick = function() {
            localStorage.removeItem('userInfo');
            window.location.href = 'login.html';
        };
    })();
    </script>
</body>
</html> 